

import React from 'react';
import PropTypes from 'prop-types';
import {injectIntl} from './intl';
import {Card, Button, Form, Row, Col, Collapse, message, Radio, Spin} from 'antd';
const Panel = Collapse.Panel;
import {FORM_BIG_OPTIONS, PAGE, FORM_ROW_OPTIONS} from '../constants';
import routes from './routes';
import CommonDetail from './CommonDetail';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import Return from '../common/Return';
import FileUpload from './FileUpload';
const autosize = {min: 1};
const bodyStyle = {
    padding: 0
};
export class Approve extends React.PureComponent {
    state = {
        visible: false,
        loading: false,
        isValidate: false,
        hasOperat: false,
        approveComment: '',
        confirmComment: '',
        dealResult: '',
        remark: '',
    }

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }
    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }
    
    handleFilterChange = (value, name) => {
        if(this.state.hasOperat)
            this.setState({[name]: value});
        else
            this.setState({
                hasOperat: true,
                [name]: value
            });
    }

    handleStatusChange = e => {
        if(e.target.value)
            this.setState({
                hasOperat: true,
                isApproved: e.target.value,
                approveComment: e.target.value ? 'PASS' : ''
            });
        else
            this.setState({
                hasOperat: true,
                isApproved: e.target.value,
                approveComment: e.target.value ? 'PASS' : ''
            });
    }
    handlePiStatusChange = e => {
        if(this.state.hasOperat)
            this.setState({isConfirmed: e.target.value});
        else
            this.setState({
                hasOperat: true,
                isConfirmed: e.target.value
            });
    }
    submit = () => {
        if(this.props.page === 'approve') {
            if(this.state.isApproved === undefined || this.state.isApproved === null) {
                this.setState({isValidate: true});
                return message.warn(this.props.intl.formatMessage({
                    id: 'approve.submit.isApproved.validate',
                    defaultMessage: '审核状态不能为空'
                }));
            }
            if(!this.state.approveComment || !this.state.approveComment.trim()) {
                this.setState({isValidate: true});
                return message.warn(this.props.intl.formatMessage({
                    id: 'approve.submit.approveComment.validate',
                    defaultMessage: '审核意见不能为空'
                }));
            }
        }
        if(this.props.page === 'confirmPi') {
            if(this.state.isConfirmed === undefined || this.state.isConfirmed === null) {
                this.setState({isValidate: true});
                return message.warn(this.props.intl.formatMessage({
                    id: 'approve.submit.isConfirmed.validate',
                    defaultMessage: '确认状态不能为空'
                }));
            }
            if(!this.state.isConfirmed && !this.state.confirmComment) {
                this.setState({isValidate: true});
                return message.warn(this.props.intl.formatMessage({
                    id: 'approve.submit.confirmComment.validate',
                    defaultMessage: '确认意见不能为空'
                }));
            }
        }
        if(this.props.page === 'confirm')
            if(this.props.conditions.piAttachments.length === 0) {
                this.setState({isValidate: true});
                return message.warn(this.props.intl.formatMessage({
                    id: 'approve.submit.piAttachments.validate',
                    defaultMessage: 'PI附件不能为空'
                }));
            }
        
        if(this.props.page === 'moreApprove') {
            if(this.state.isApproved === undefined || this.state.isApproved === null) {
                this.setState({isValidate: true});
                return message.warn(this.props.intl.formatMessage({
                    id: 'approve.submit.isApproved.validate',
                    defaultMessage: '审核状态不能为空'
                }));
            }
            if(!this.state.approveComment || !this.state.approveComment.trim()) {
                this.setState({isValidate: true});
                return message.warn(this.props.intl.formatMessage({
                    id: 'approve.submit.approveComment.validate',
                    defaultMessage: '审核意见不能为空'
                }));
            }
        }
        this.setState({loading: true});
        if(this.props.page === 'approve')
            this.props.onClickApprove({
                isApproved: this.state.isApproved,
                approveComment: this.state.approveComment,
                dealResult: this.state.dealResult,
                remark: this.state.remark,
            }).then(success => {
                if(this.ismounted && !success)
                    this.setState({loading: false});
            });
        if(this.props.page === 'confirmPi')
            this.props.onClickConfirmPi({
                isConfirmed: this.state.isConfirmed,
                confirmComment: this.state.confirmComment,
            }).then(success => {
                if(this.ismounted && !success)
                    this.setState({loading: false});
            });
        if(this.props.page === 'confirm')
            this.props.onClickConfirm({
            }).then(success => {
                if(this.ismounted && !success)
                    this.setState({loading: false});
            });
        if(this.props.page === 'moreApprove')
            this.props.onClickMoreApprove({
                isApproved: this.state.isApproved,
                approveComment: this.state.approveComment
            }).then(success => {
                if(this.ismounted && !success)
                    this.setState({loading: false});
            });
    }
    
    onChangeUpload = data => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.updatePiAttachments(data);
    }
    render() {
        const operations = [];
        const {piAttachments = []} = this.props.conditions;
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Card bodyStyle={bodyStyle}>
                        <Collapse defaultActiveKey="1" bordered={false}>
                            <Panel header={this.props.intl.formatMessage({
                                id: 'approve.detail.panel',
                                defaultMessage: '扣补款单详情'
                            })} key="1" forceRender>
                                <CommonDetail isDealerUser={this.props.isDealerUser} detail={this.props.detail} page={this.props.page}/>
                            </Panel>
                        </Collapse>
                    </Card>
                    {this.props.page === 'approve' && <Form className="form-standard">
                        <Card
                            className={styles.marginBottom}
                            extra={operations}
                            title={this.props.intl.formatMessage({
                                id: 'approve.card.title',
                                defaultMessage: '审核信息'
                            })}>
                            <Row className="radio-group-validate">
                                <Col {...FORM_BIG_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'approve.form.isApproved',
                                        defaultMessage: '审核状态'
                                    })} {...FORM_BIG_OPTIONS.item} required>
                                        <RadioGroup onChange={this.handleStatusChange} value={this.state.isApproved}>
                                            <Radio value={true}>{this.props.intl.formatMessage({
                                                id: 'approve.form.pass',
                                                defaultMessage: '通过'
                                            })}</Radio>
                                            <Radio value={false}>{this.props.intl.formatMessage({
                                                id: 'approve.form.reject',
                                                defaultMessage: '不通过'
                                            })}</Radio>
                                        </RadioGroup>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'approve.form.panel',
                                        defaultMessage: '审核意见'
                                    })} {...FORM_ROW_OPTIONS.item} required
                                    validateStatus={this.state.isValidate && !this.state.approveComment ? 'error' : null}>
                                        <TextInput
                                            type="textarea"
                                            id="approveComment"
                                            autosize={autosize}
                                            value={this.state.approveComment}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'approve.form.dealResult',
                                        defaultMessage: '处理结果'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            type="textarea"
                                            id="dealResult"
                                            autosize={autosize}
                                            value={this.state.dealResult}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'approve.form.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            type="textarea"
                                            id="remark"
                                            autosize={autosize}
                                            value={this.state.remark}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                    </Form>}
                    {this.props.page === 'confirm' && <Form className="form-standard">
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'approve.card.piFileList.title',
                                defaultMessage: 'PI附件'
                            })}
                            className={styles.marginBottom}>
                            <Row>
                                <Col {...FORM_BIG_OPTIONS.col}>
                                    <FileUpload onChange={this.onChangeUpload} onRemove={this.props.removePiAttachments} fileList={piAttachments} />
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                    }
                    {this.props.page === 'confirmPi' && <Form className="form-standard">
                        <Card
                            className={styles.marginBottom}
                            extra={operations}
                            title={this.props.intl.formatMessage({
                                id: 'confirmPi.card.title',
                                defaultMessage: '确认信息'
                            })}>
                            <Row className="radio-group-validate">
                                <Col {...FORM_BIG_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'confirmPi.form.isConfirmed',
                                        defaultMessage: '确认状态'
                                    })} {...FORM_BIG_OPTIONS.item} required>
                                        <RadioGroup onChange={this.handlePiStatusChange} value={this.state.isConfirmed}>
                                            <Radio value={true}>{this.props.intl.formatMessage({
                                                id: 'confirmPi.form.pass',
                                                defaultMessage: '通过'
                                            })}</Radio>
                                            <Radio value={false}>{this.props.intl.formatMessage({
                                                id: 'confirmPi.form.reject',
                                                defaultMessage: '驳回'
                                            })}</Radio>
                                        </RadioGroup>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'confirmPi.form.panel',
                                        defaultMessage: '确认意见'
                                    })} {...FORM_ROW_OPTIONS.item} required={!this.state.isConfirmed}
                                    validateStatus={this.state.isValidate && !this.state.confirmComment ? 'error' : null}>
                                        <TextInput
                                            type="textarea"
                                            id="confirmComment"
                                            autosize={autosize}
                                            value={this.state.confirmComment}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                    }
                    {this.props.page === 'moreApprove' && <Form className="form-standard">
                        <Card
                            className={styles.marginBottom}
                            extra={operations}
                            title={this.props.intl.formatMessage({
                                id: 'approve.card.title',
                                defaultMessage: '审核信息'
                            })}>
                            <Row className="radio-group-validate">
                                <Col {...FORM_BIG_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'approve.form.isApproved',
                                        defaultMessage: '审核状态'
                                    })} {...FORM_BIG_OPTIONS.item} required>
                                        <RadioGroup onChange={this.handleStatusChange} value={this.state.isApproved}>
                                            <Radio value={true}>{this.props.intl.formatMessage({
                                                id: 'approve.form.pass',
                                                defaultMessage: '通过'
                                            })}</Radio>
                                            <Radio value={false}>{this.props.intl.formatMessage({
                                                id: 'approve.form.reject',
                                                defaultMessage: '不通过'
                                            })}</Radio>
                                        </RadioGroup>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'approve.form.panel',
                                        defaultMessage: '审核意见'
                                    })} {...FORM_ROW_OPTIONS.item} required
                                    validateStatus={this.state.isValidate && !this.state.approveComment ? 'error' : null}>
                                        <TextInput
                                            type="textarea"
                                            id="approveComment"
                                            autosize={autosize}
                                            value={this.state.approveComment}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                    </Form>}
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
                
                <Card type="inner">
                    <Row>
                        <Col className="col-align-right">
                            <Button key="approve" loading={this.state.loading}
                                onClick={this.submit} type="primary">{this.props.intl.formatMessage({
                                    id: 'approve.btn.submit',
                                    defaultMessage: '保存'
                                })}</Button>
                        </Col>
                    </Row>
                </Card>
                
            </div>
        );
    }
}

Approve.propTypes = {
    detail: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    removeAttachments: PropTypes.func.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickApprove: PropTypes.func.isRequired,
    onClickConfirm: PropTypes.func.isRequired,
    onClickMoreApprove: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    intl: PropTypes.object,
    page: PropTypes.string
};

import {connect} from 'react-redux';
import {
    getDetail,
    clearData,
    tableSearch,
    onClickApprove,
    onClickConfirm,
    onClickConfirmPi,
    updatePiAttachments,
    removePiAttachments,
    onClickMoreApprove
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
import {PERMISSION} from './constants';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);
const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);
const getSubmitable = createSelector(
    state => getPermissions(state),
    state => getDetailData(state),
    (permission, detail) => {
        const {options = []} = detail;
        return (options.includes(PERMISSION.confirm) && permission.includes(PERMISSION.confirm)) ||
         (options.includes(PERMISSION.approve) && permission.includes(PERMISSION.approve));
    }
);
const mapStateToProps = (state, ownProps) => ({
    loading: state.getIn((['page', 'domainData', 'detail', 'isFetching'])) || state.getIn(['page', 'domainData', 'initData', 'isFetching']),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    detail: getDetailData(state),
    submitable: getSubmitable(state, ownProps),
    conditions: getSubmitData(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onClickApprove: data => dispatch(onClickApprove(ownProps.id, data)).then(success => {
        if(success) {
            dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            ownProps.history.push(routes.query.url());
        }
        return success;
    }),
    onClickConfirmPi: data => dispatch(onClickConfirmPi(ownProps.id, data)).then(success => {
        if(success) {
            dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            ownProps.history.push(routes.query.url());
        }
        return success;
    }),
    onClickConfirm: () => dispatch(onClickConfirm(ownProps.id)).then(success => {
        if(success) {
            dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            ownProps.history.push(routes.query.url());
        }
        return success;
    }),
    onUmount: () => dispatch(clearData()),
    updatePiAttachments: data => dispatch(updatePiAttachments(data)),
    removePiAttachments: ({id}) => dispatch(removePiAttachments(id)),
    onClickMoreApprove: data => dispatch(onClickMoreApprove(ownProps.id, data)).then(success => {
        if(success) {
            dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            ownProps.history.push(routes.query.url());
        }
        return success;
    })
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(Approve));
